package com.phpxiu.app.view.dialog;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.phpxiu.app.adapter.CommonMsgListAdapter;
import com.phpxiu.app.adapter.CommonOnlineListAdapter;
import com.phpxiu.app.adapter.holder.CommonMsgViewHolder;
import com.phpxiu.app.api.callback.MsgCountManager;
import com.phpxiu.app.api.listener.BaseAnimationListener;
import com.phpxiu.app.api.listener.OnlineItemClickListener;
import com.phpxiu.app.api.listener.WindowLayoutListener;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.LiveRoomInfo;
import com.phpxiu.app.model.MemberInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.MsgSender;
import com.phpxiu.app.model.gift.Gift;
import com.phpxiu.app.model.gift.GiftAnim;
import com.phpxiu.app.model.msg.CommonMsg;
import com.phpxiu.app.model.msg.EnterMsg;
import com.phpxiu.app.model.msg.GoodMsg;
import com.phpxiu.app.model.msg.IMGiftMsg;
import com.phpxiu.app.model.msg.ManageMsg;
import com.phpxiu.app.model.msg.SystemMsg;
import com.phpxiu.app.model.msg.UpdateOnlineMsg;
import com.phpxiu.app.model.response.MsgModel;
import com.phpxiu.app.model.response.RobotModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.RoomPresenter;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.RoomVideoRoom;
import com.phpxiu.app.view.Main;
import com.phpxiu.app.view.custom.FlyWordsView;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.phpxiu.app.view.custom.GiftAnimView;
import com.phpxiu.app.view.custom.ImageSurfaceView;
import com.phpxiu.app.view.custom.MPraiseAnimView;
import com.phpxiu.app.view.custom.WindowLayout;
import com.tencent.TIMCustomElem;
import com.tencent.TIMElem;
import com.tencent.TIMFriendshipManager;
import com.tencent.TIMGroupManager;
import com.tencent.TIMGroupMemberInfo;
import com.tencent.TIMGroupMemberSuccV2;
import com.tencent.TIMMessage;
import com.tencent.TIMTextElem;
import com.tencent.TIMUserProfile;
import com.tencent.TIMValueCallBack;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by 吴金洲 on 2016/6/25
 */
public class LiveRoomAnimWin extends Dialog implements View.OnClickListener,Observer,
        WindowLayoutListener,OnlineItemClickListener,GiftPanel.GiftPanelOperaCallBack{
    public final static String TAG="LiveRoomAnimWin";
    private final static int DISTANCE_SLOP = 350;
    private final static int SHOW_MSG=0x101;//显示消息到列表
    private final static int INSERT_GIFT_ANIM=0x111;
    private final static int READ_GIFT_ANIM=0x112;
    private final static int ANIM_READY=0x113;
    private final static int CHECK_CONTINUE=0x114;
    private final static int ANIM_FINISH_0=0x115;
    private final static int ANIM_FINISH_1=0x116;
    private final static int ANIM_HIDE=0x117;
    private final static int INSERT_FRAME_GIFT_ANIM=0x118;
    private final static int READ_FRAME_GIFT_ANIM=0x119;
    private final static int CLEAR_FRAME_GIFT_ANIM=0x120;
    private final static int HANDLE_SEND_LIKE=0x121;//发送点赞消息
    public final static int HANDLE_REPLY_MSG=0x123;//回复消息
    public final static int HANDLE_HIDE_ATTENTION=0x124;//执行隐藏关注按钮动画
    public final static int HANDLE_HIDE_MULTI_VIDEO_BTN=0x125;
    public final static int HANDLE_SHOW_MULTI_VIDEO_BTN=0x126;
    public final static int HANDLE_UPDATE_MSG_COUNT=0x127;//更新消息数量
    public final static int HANDLE_REFRESH_ONLINE_BY_ENTER=0x128;//进入房间刷新列表
    public final static int HANDLE_REFRESH_ONLINE_BY_EXIT=0x129;//离开房间刷新列表
    public final static int HANDLE_HOST_BROADCAST_ONLINE=0x130;//主播广播在线人数
    public final static int HANDLE_UPDATE_ONLINE_COUNT=0x131;//根据主播广播在线人数更新显示的在线人数值
    public final static int HANDLE_FLASHLIGHT_STATE_REFRESH=0x132;//闪光灯标志状态切换
    public final static int HANDLE_SHOW_JOIN_MSG=0x133;//显示进入房间消息
    public final static int HANDLE_HIDE_JOIN_MSG_VIEW=0x134;//隐藏进入房间消息
    protected final static String MUTE_STATE="kky_mute_state";
    protected final static String MUTE_EXPIRE_AT="kky_mute_expire_at";//禁言结束时间
    protected final static long MAX_MUTE_TIME=10*60*1000;//禁言时长为10分钟
    protected RoomPresenter roomPresenter;
    protected Gson gson= new Gson();
    private Rect mMsgBoxRect=new Rect();
    protected int mScreenWidth,mScreenHeight;
    protected LiveRoomInfo roomInfo;
    private String memberId;
    private boolean attention=false;//是否关注
    protected WindowLayout mainView;

    private LinearLayout topBox;
    protected FrescoImageView topHeadView;
    protected TextView topOnlineTv;
    private ImageButton attentionBtn;
    protected AnimatorSet attentionBtnHideAnim;

    //在线观众列表
    protected RecyclerView onlineListView;
    protected LinearLayoutManager layoutManager;
    protected CommonOnlineListAdapter mOnlineAdapter;
    private ConcurrentHashMap<String,String> onlineIds=new ConcurrentHashMap<String,String>();
    private List<MemberInfo> members=new ArrayList<MemberInfo>();//在线人数列表
    private long mNextSeq=0;//返回值mNextSeq不为零，则表示有下一页数据，直播大群只能拉取部份成员列表，见文档资料说明
    private boolean isLoadedRobotList=false;//已加载机器人列表
    private long mRealOnlineCount=0;//真实在线人数
    private int mRobotCount=0;
    private long mOnlineCount=mRealOnlineCount+mRobotCount;//在线人数 真实人数+机器人数(固定)
    private final int MIN_RANDOM_COUNT=5;
    private final int MAX_RANDOM_COUNT=15;
    private final Random countRandom=new Random();
    private MsgModel updateOnlineMsg=new MsgModel();
    private UpdateOnlineMsg updateOnline=new UpdateOnlineMsg("0");
    private boolean isBroadcastOnline=true;//只有玩家进入事件才会转变此状态
    private boolean isCountRobots=true;

    protected long currentGain=0;//当前获得总票数
    protected LinearLayout currentGainLink;//排行连接菜单
    private Rect currentGainLinkRect=new Rect();
    protected TextView gainValueTv;//总票数显示控件
    private String gainLabel;
    private SpannableStringBuilder ticketsCountText=new SpannableStringBuilder();
    private ForegroundColorSpan TICKETS_SPAN=new ForegroundColorSpan(Color.parseColor("#ff24A8DF"));

    private Animation topBoxEnterAni,topBoxOutAni;
    private AnimatorSet userGainBtnEnterAnim,userGainBtnOutAnim;
    private ObjectAnimator userGainBtnEnterX,userGainBtnOutX;

    private GiftAnimView animViewFirst,animViewSecond;
    private Timer checkGiftAnimListTimer=new Timer(true);//礼物动画列表检查定时器
    private TimerTask checkGiftAnimListTask;//礼物动画列表检查定时器任务，每500ms检测一次
    private List<GiftAnim>giftAnimList=new ArrayList<GiftAnim>();

    protected RelativeLayout msgBox;
    private ListView msgListView;
    private CommonMsgListAdapter msgListAdapter;
    private List<Object>msgList=new ArrayList<Object>();
    private TextView joinMsgView;
    private ForegroundColorSpan JOIN_COLOR_SPAN=new ForegroundColorSpan(Color.parseColor("#ffCED1D4"));
    private SpannableStringBuilder JOIN_MSG=new SpannableStringBuilder();
    private String joinMsgSuffix;
    private int mLvSpanWidth;
    private int mLvSpanHeight;

    protected RelativeLayout mBottomBarMenus;
    private LinearLayout hostControlView,memberControlView;
    protected TextView msgCountView;//私信消息未读数量显示
    private long msgCount=0L;
    protected ImageButton openInputBtn;//输入聊天信息
    protected RelativeLayout msgBoardBtn;
    protected ImageButton hostShareBtn,shareMenuBtn;
    protected ImageButton openGiftBoardBtn;
    protected ImageButton cameraSettingsBtn;
    private ImageButton exitWindowBtn;//结束直播间
    private Animation bottomBarOutAnim;

    protected RelativeLayout mInputBar;
    private Rect inputBarRect=new Rect();
    protected EditText mInput;
    protected Button sendMsgBtn;
    private boolean isShowKeyBoard=false;//键盘显示

    private MPraiseAnimView praiseAnimView;
    private boolean isFirstHeart=true;//true第一次发送点赞消息，此次点赞会显示一条消息在聊天列表中，形如xxx:我点亮了[xxx颜色心形]
    private String praiseColorCode="1";//点赞动画的颜色代码1-7，某一个用户会绑定一个固定的颜色代码，根据用户的id生成value=id%7;
    private Timer checkPraiseCountTimer=new Timer(true);//检测点击屏幕次数的定时器，定时执行checkPraiseCountTask
    private TimerTask checkPraiseCountTask;//检测点击屏幕次数的任务，用于统计每秒内点赞的数量
    private int countPerSecond=0;//每秒的点赞数量

    private MsgModel msgModel;
    private GoodMsg goodMsg;//赞消息体
    private int hostGoodCount=0;
    protected MsgSender mMsgSender;
    protected GiftPanel giftPanel;
    protected ImageSurfaceView framesAnimView;//帧动画
    private RelativeLayout.LayoutParams framesAnimViewLayoutParam;
    private List<IMGiftMsg>frameAnimList=new ArrayList<IMGiftMsg>();//大礼物动画队列
    private Timer readFrameAnimTimer=new Timer(true);
    private TimerTask readFrameAnimTask;
    private boolean isPlayFrameAnim=false;//正在播放帧动画

    protected Handler handler;
    protected SharedPreferences sp;
    private long liveIncoming=0;

    protected ImageButton multiVideoBtn;//成员连麦操作按钮,只会在满足开启连麦功能且不处于互动状态的成员端显示

    protected RoomVideoRoom mRoom;

    private FlyWordsView flyWordsView;//弹幕视图


    @Deprecated
    private ImageButton openWebGame,openWebGame_;//打开游戏界面按钮

    protected ImageButton flashlightSwitch;//闪光灯状态切换按钮
    protected boolean flashlightOff=true;//闪光灯默认为关闭状态
    protected boolean isCanSwitchLight=false;//是否能切换闪光灯，前置摄像头不能切换

    protected int currentLvl=MySelfInfo.getInstance().getLvl();

    public LiveRoomAnimWin(RoomVideoRoom liveRoom,LiveRoomInfo roomInfo) {
        super(liveRoom, R.style.roomDialog);
        this.roomInfo=roomInfo;
        mOnlineCount=roomInfo.getOnline();
        mRoom=liveRoom;
        mScreenHeight=(int) KKYApp.getInstance().screenHeight;
        mScreenWidth=(int) KKYApp.getInstance().screenWidth;
        memberId= MySelfInfo.getInstance().getId();
        if(memberId!=null&&!"".equals(memberId)) {
            try {
                long id = Long.parseLong(memberId);
                praiseColorCode=((id%7)+1)+"";
            } catch (NumberFormatException e) {

            }
        }
        init();
    }

    protected void init(){
        setContentView(R.layout.live_room_win);
        handler=new IHandler(this);
        mainView=(WindowLayout)findViewById(R.id.main_room_window);
        mainView.addWindowLayoutListener(this);
        mainView.setOnClickListener(this);
        flyWordsView=(FlyWordsView)findViewById(R.id.main_room_fly_word_container);
        initTopView();
        initGiftAnimView();
        initFrameAnim();
        initMsgBox();
        initPraiseView();
        initBottomBar();
        initMsgCount();
        initGiftPanel();
    }

    private void initTopView(){
        topBox=(LinearLayout)findViewById(R.id.main_room_window_top_box);
        topHeadView=(FrescoImageView)findViewById(R.id.main_room_window_user_info_head_view);
        topHeadView.setOnClickListener(this);
        try {
            topHeadView.setImageURI(Uri.parse(CurLiveInfo.getHostAvator()));
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        topOnlineTv=(TextView)findViewById(R.id.main_room_window_online_info);
        topOnlineTv.setText(mOnlineCount+"");
        //如果是观众，判断关注状态
        if(MySelfInfo.getInstance().getIdStatus()== Constants.MEMBER) {
            attention ="1".equals(roomInfo.getRelationship())||"2".equals(roomInfo.getRelationship());
            attentionBtn = (ImageButton) findViewById(R.id.main_room_attention_opera_btn);
            if (!attention) {
                attentionBtn.setVisibility(View.VISIBLE);
                attentionBtn.setOnClickListener(this);
                attentionBtnHideAnim = new AnimatorSet();
                ObjectAnimator scaleX = ObjectAnimator.ofFloat(attentionBtn, View.SCALE_X, 1f, 0f);
                attentionBtnHideAnim.play(scaleX);
                attentionBtnHideAnim.setDuration(500);
                attentionBtnHideAnim.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        attentionBtn.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                handler.sendEmptyMessageDelayed(HANDLE_HIDE_ATTENTION, 10000);
            }
        }
        //在线观众列表
        onlineListView=(RecyclerView)findViewById(R.id.main_room_window_online_list_view);
        layoutManager=new LinearLayoutManager(mRoom);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        onlineListView.setLayoutManager(layoutManager);
        mOnlineAdapter=new CommonOnlineListAdapter(mRoom,members);
        mOnlineAdapter.addOnItemClickListener(this);
        onlineListView.setAdapter(mOnlineAdapter);
        onlineListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastPosition = layoutManager.findLastVisibleItemPosition();
                    int totalCount = layoutManager.getItemCount();
                    if (lastPosition == (totalCount - 1)) {
                        //加载下页
                        if(mNextSeq!=0){
                            loadOnline(mNextSeq);
                        }
                    }
                    if(isCountRobots){//没有计算机器人数
                        if(mOnlineCount<members.size()){//在线数小于实际列表数
                            if(mRobotCount>0){//有机器人数
                                isCountRobots=false;
                                isBroadcastOnline=true;
                                handler.sendEmptyMessage(HANDLE_HOST_BROADCAST_ONLINE);
                            }
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        topBoxOutAni= AnimationUtils.loadAnimation(getContext(), R.anim.common_top_box_out);
        topBoxOutAni.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                topBox.setVisibility(View.GONE);
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        topBoxEnterAni=AnimationUtils.loadAnimation(getContext(), R.anim.common_top_box_enter);
        currentGainLink=(LinearLayout)findViewById(R.id.gain_link);
        currentGainLink.setOnClickListener(this);
        gainLabel=getContext().getString(R.string.ui_room_tickets_title);
        gainValueTv=(TextView)currentGainLink.findViewById(R.id.current_gain_value);
        if(TextUtils.isDigitsOnly(roomInfo.getVote())){
            currentGain=Long.parseLong(roomInfo.getVote());
        }

        refreshTicketsCount();
        userGainBtnEnterAnim=new AnimatorSet();
        userGainBtnEnterX=ObjectAnimator.ofFloat(currentGainLink,View.TRANSLATION_X,-300,0);
        userGainBtnEnterAnim.play(userGainBtnEnterX).with(ObjectAnimator.ofFloat(currentGainLink,View.TRANSLATION_Y,0,0));
        userGainBtnEnterAnim.setDuration(500);
        userGainBtnOutAnim=new AnimatorSet();
        userGainBtnOutX=ObjectAnimator.ofFloat(currentGainLink,View.TRANSLATION_X,0,-300);
        userGainBtnOutAnim.play(userGainBtnOutX).with(ObjectAnimator.ofFloat(currentGainLink,View.TRANSLATION_Y,0,0));
        userGainBtnOutAnim.setDuration(500);
        userGainBtnOutAnim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                currentGainLink.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    /**
     * 初始化送礼动画
     */
    private void initGiftAnimView(){
        animViewFirst=(GiftAnimView)findViewById(R.id.main_room_window_gift_anim_first_view);
        animViewFirst.setOperaLabel(getContext().getString(R.string.list_gift_msg));
        animViewFirst.bigNumAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                if(animViewFirst.changeNum()){
                    animViewFirst.resetAnim();
                    Message msg = handler.obtainMessage();
                    msg.what = CHECK_CONTINUE;
                    msg.obj = 0;
                    handler.sendMessageDelayed(msg,300);//600ms后检测是否继续
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        animViewFirst.smallNumAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Message msg = handler.obtainMessage();
                msg.what = CHECK_CONTINUE;
                msg.obj = 0;
                handler.sendMessage(msg);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        animViewFirst.enterAnim.setAnimationListener(new BaseAnimationListener(){
            @Override
            public void onAnimationStart(Animation animation) {

            }
            @Override
            public void onAnimationEnd(Animation animation) {
                Message msg=handler.obtainMessage();
                msg.what=ANIM_READY;
                msg.obj=0;
                handler.sendMessage(msg);
            }
        });

        animViewFirst.outAnim.setAnimationListener(new BaseAnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Message msg = handler.obtainMessage();
                msg.what = ANIM_HIDE;
                msg.obj = 0;
                handler.sendMessage(msg);
            }
        });
        animViewSecond=(GiftAnimView)findViewById(R.id.main_room_window_gift_anim_second_view);
        animViewSecond.setOperaLabel(getContext().getString(R.string.list_gift_msg));
        animViewSecond.bigNumAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                //计数失败，则检测是否继续
                if(animViewSecond.changeNum()){
                    animViewSecond.resetAnim();
                    Message msg = handler.obtainMessage();
                    msg.what = CHECK_CONTINUE;
                    msg.obj = 1;
                    handler.sendMessageDelayed(msg,300);//600ms后检测是否继续
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        animViewSecond.smallNumAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Message msg = handler.obtainMessage();
                msg.what = CHECK_CONTINUE;
                msg.obj = 1;
                handler.sendMessage(msg);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        animViewSecond.enterAnim.setAnimationListener(new BaseAnimationListener(){
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Message msg=handler.obtainMessage();
                msg.what=ANIM_READY;
                msg.obj=1;
                handler.sendMessage(msg);
            }
        });

        animViewSecond.outAnim.setAnimationListener(new BaseAnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Message msg = handler.obtainMessage();
                msg.what = ANIM_HIDE;
                msg.obj = 1;
                handler.sendMessage(msg);
            }
        });
    }

    /**
     * 初始化帧动画控件
     */
    private void initFrameAnim(){
        framesAnimView=(ImageSurfaceView)findViewById(R.id.gift_anim_surface_view);
        //framesAnimViewLayoutParam=(RelativeLayout.LayoutParams)framesAnimView.getLayoutParams();
        //framesAnimViewLayoutParam.height=mScreenWidth;
        //framesAnimView.setLayoutParams(framesAnimViewLayoutParam);
        framesAnimView.setSurfaceViewPlayListener(new ImageSurfaceView.OnAnimSurfaceViewPlayListener() {
            @Override
            public void onAnimSurfaceViewEnd() {
                handler.sendEmptyMessage(CLEAR_FRAME_GIFT_ANIM);
            }
        });

    }

    /**
     * 初始化消息列表
     */
    private void initMsgBox(){
        joinMsgSuffix=getContext().getString(R.string.list_join_msg);
        mLvSpanWidth= KKYUtil.dip2px(getContext(), 32.0f);
        mLvSpanHeight= KKYUtil.dip2px(getContext(), 14f);
        msgBox=(RelativeLayout)findViewById(R.id.main_room_window_msg_box);
        msgBox.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (isKeyboardVisible(msgBox)) {
                    if(isShowKeyBoard==false) {
                        isShowKeyBoard = true;
                    }
                } else {
                    if (isShowKeyBoard) {
                        onBoardHide();
                        isShowKeyBoard = false;
                    }
                }
                return true;
            }
        });
        joinMsgView=(TextView)findViewById(R.id.common_chat_msg_join_msg_view);
        msgListView=(ListView)findViewById(R.id.main_room_window_msg_list_view);
        msgListView.setDivider(null);
        msgList.addAll(Main.SYSTEM_MSG);
        msgListAdapter=new CommonMsgListAdapter(mRoom,msgList);
        msgListAdapter.setWin(this);
        msgListView.setAdapter(msgListAdapter);
    }


    /**
     * 初始化心形动画内容
     */
    private void initPraiseView(){
        praiseAnimView=(MPraiseAnimView)findViewById(R.id.main_room_window_heart_view_box);
        //主播不能点赞
        if(MySelfInfo.getInstance().getIdStatus()==Constants.MEMBER) {
            if (checkPraiseCountTask == null) {
                checkPraiseCountTask = new TimerTask() {
                    @Override
                    public void run() {
                        checkSendPraise(true);
                    }
                };
            }
            checkPraiseCountTimer.schedule(checkPraiseCountTask, 0, 1000);
        }
    }

    /**
     * 检测是否发送点赞消息
     * @param isCheckSend true在此一时刻的前一秒内，点赞数不为零，则发送点赞消息，否则累计点赞数量
     */
    private synchronized void checkSendPraise(boolean isCheckSend){
        if(isCheckSend){
            if(countPerSecond!=0){
                Message msg=handler.obtainMessage();
                msg.what=HANDLE_SEND_LIKE;
                msg.obj=countPerSecond+"";
                handler.sendMessage(msg);
                countPerSecond=0;
            }
        }else{
            countPerSecond++;
        }
    }

    /**
     * 发送点赞消息到服务器
     */
    private void sendPraise(String num){
        if(msgModel==null){
            msgModel=new MsgModel();
        }
        if(goodMsg==null){
            goodMsg=new GoodMsg();
        }
        msgModel.setUserAction(Constants.AVIMCMD_Praise);
        goodMsg.setFuser(null);
        goodMsg.setNum(num);
        goodMsg.setStar(praiseColorCode);
        if(isFirstHeart){
            msgModel.setUserAction(Constants.AV_IM_CMD_NOTICE_GOOD);
            if(mMsgSender ==null){
                mMsgSender =new MsgSender();
                mMsgSender.setUid(MySelfInfo.getInstance().getId());
                mMsgSender.setNickname(MySelfInfo.getInstance().getNickName());
                mMsgSender.setLvl(MySelfInfo.getInstance().getLvl());
            }
            goodMsg.setFuser(mMsgSender);
            isFirstHeart=false;
        }
        msgModel.setActionParam(gson.toJson(goodMsg));
        roomPresenter.sendGroupNoticeMsg(gson.toJson(msgModel), goodMsgCallBack);//低级别消息
    }

    private TIMValueCallBack<TIMMessage> goodMsgCallBack=new TIMValueCallBack<TIMMessage>() {
        @Override
        public void onError(int i, String s) {
        }

        @Override
        public void onSuccess(TIMMessage timMessage) {
            //自己点赞
           if(timMessage.getSender().equals(MySelfInfo.getInstance().getId())){
               TIMElem elem=timMessage.getElement(0);
               try {
                   String json = new String(((TIMCustomElem) elem).getData(), "UTF-8");
                   MsgModel msgModel=gson.fromJson(json,MsgModel.class);
                   GoodMsg goodMsg=gson.fromJson(msgModel.getActionParam(),GoodMsg.class);
                   if(goodMsg.getFuser()!=null){//首次点赞
                       hostGoodCount++;//累加点赞量
                       CurLiveInfo.setAdmires(hostGoodCount);
                       goodMsg.setShowInList(true);
                       Message msg=handler.obtainMessage();
                       msg.what=SHOW_MSG;
                       msg.obj=goodMsg;
                       handler.sendMessage(msg);
                   }
               }catch (IOException e){

               }
           }
        }
    };



    private void initBottomBar(){
        mBottomBarMenus=(RelativeLayout)findViewById(R.id.main_room_window_bottom_bar_opera_menus);
        openInputBtn=(ImageButton)findViewById(R.id.main_room_window_open_input_btn);
        openInputBtn.setOnClickListener(this);
        //连麦视图初始化
        multiVideoBtn=(ImageButton)findViewById(R.id.multi_video_opera_btn);
        multiVideoBtn.setOnClickListener(this);
        if(MySelfInfo.getInstance().getIdStatus()==Constants.HOST){//主播默认不可以主动发起连麦
            if(multiVideoBtn.getVisibility()==View.VISIBLE){
                multiVideoBtn.setVisibility(View.GONE);
            }
        }else {
            //等级大于5级可连麦
            if(currentLvl>=Constants.INTERACT_MIN_LVL) {
                if (multiVideoBtn.getVisibility() != View.VISIBLE) {
                    multiVideoBtn.setVisibility(View.VISIBLE);
                }
            }
        }
        mInputBar=(RelativeLayout)findViewById(R.id.main_room_window_bottom_bar_input_bar);
        mInput=(EditText)findViewById(R.id.main_room_window_bottom_bar_input);
        sendMsgBtn=(Button)findViewById(R.id.main_room_window_bottom_bar_send_btn);
        sendMsgBtn.setOnClickListener(this);
        msgBoardBtn=(RelativeLayout)findViewById(R.id.main_room_window_open_msg_board_btn);
        msgBoardBtn.setOnClickListener(this);
        msgCountView=(TextView)findViewById(R.id.c2c_conversation_un_read_count_view);
        if(MySelfInfo.getInstance().getIdStatus()== Constants.HOST){
            hostControlView=(LinearLayout)findViewById(R.id.main_room_window_bottom_host_bar);
            hostControlView.setVisibility(View.VISIBLE);
            exitWindowBtn=(ImageButton)findViewById(R.id.main_room_window_host_exit_btn);
            exitWindowBtn.setOnClickListener(this);
        }else {
            memberControlView=(LinearLayout)findViewById(R.id.main_room_window_bottom_member_bar);
            memberControlView.setVisibility(View.VISIBLE);
            exitWindowBtn=(ImageButton)findViewById(R.id.main_room_window_exit_btn);
            exitWindowBtn.setOnClickListener(this);
        }
        shareMenuBtn=(ImageButton)findViewById(R.id.main_room_window_open_share_menus_btn);
        hostShareBtn=(ImageButton)findViewById(R.id.main_room_window_host_open_share_menus_btn);
        if("1".equals(roomInfo.getType())){
            KKYUtil.log("当前直播为私密直播");
            shareMenuBtn.setVisibility(View.GONE);
            hostShareBtn.setVisibility(View.GONE);
        }else{//私密直播不分享
            shareMenuBtn.setOnClickListener(this);
            hostShareBtn.setOnClickListener(this);
        }
        openGiftBoardBtn=(ImageButton)findViewById(R.id.main_room_window_open_gift_box_btn);
        openGiftBoardBtn.setOnClickListener(this);
        cameraSettingsBtn=(ImageButton)findViewById(R.id.main_room_window_camera_menus_btn);
        cameraSettingsBtn.setOnClickListener(this);
        flashlightSwitch=(ImageButton)findViewById(R.id.main_room_window_flashlight_menus_btn);
        flashlightSwitch.setOnClickListener(this);
        bottomBarOutAnim=AnimationUtils.loadAnimation(getContext(), R.anim.commom_bottom_bar_out);
        bottomBarOutAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mBottomBarMenus.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //打开游戏界面按钮
        openWebGame=(ImageButton)findViewById(R.id.main_room_window_open_game_menus_icon);
        openWebGame.setOnClickListener(this);
        openWebGame_=(ImageButton)findViewById(R.id.main_room_window_open_game_menus_icon_);
        openWebGame_.setOnClickListener(this);
    }

    /**
     * 消息数量维护
     */
    private void initMsgCount(){
        MsgCountManager.getInstance().addObserver(this);
        MsgCountManager.getInstance().refreshMsgCount();
    }

    /**
     *更新消息数量
     * @param observable
     * @param data
     */
    @Override
    public void update(Observable observable, Object data) {
        try {
            msgCount=(long)data;
            if(handler!=null){
                handler.sendEmptyMessage(HANDLE_UPDATE_MSG_COUNT);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 更新消息数量
     */
    public void updateMsgCountView() {
        if(msgCount<100){
            if(msgCount==0){
                msgCountView.setVisibility(View.INVISIBLE);
                return;
            }
            if(msgCountView.getVisibility()!=View.VISIBLE){
                msgCountView.setVisibility(View.VISIBLE);
            }
            msgCountView.setText(msgCount+"");
        }
    }

    /**
     * 初始化礼物面板
     */
    public void initGiftPanel(){
        mainView.post(new Runnable() {
            @Override
            public void run() {
                if (giftPanel==null){
                    giftPanel=new GiftPanel(getContext());
                    giftPanel.setCallBack(LiveRoomAnimWin.this);
                    EventBus.getDefault().register(giftPanel);
                    giftPanel.getWindow().getAttributes().width=(int)KKYApp.getInstance().screenWidth;
                }
            }
        });
    }

    /**
     * 收到IM自定义消息
     */
    public void onReceiveCustomMsg(TIMMessage currMsg,TIMElem elem){
        try{
            Message msg=handler.obtainMessage();
            msg.what=SHOW_MSG;
            String json = new String(((TIMCustomElem) elem).getData(), "UTF-8");
            KKYUtil.log("自定义消息Json:" + json);
            MsgModel msgModel=gson.fromJson(json,MsgModel.class);
            switch (msgModel.getUserAction()) {
                case Constants.AV_IM_CMD_MEMBER_UPDATE_ONLINE:
                    if(MySelfInfo.getInstance().getIdStatus()==Constants.MEMBER) {
                        UpdateOnlineMsg updateOnlineMsg = gson.fromJson(msgModel.getActionParam(), UpdateOnlineMsg.class);
                        KKYUtil.log("收到在线人数变动广播：" + updateOnlineMsg.getOnline());
                        msg.what=HANDLE_UPDATE_ONLINE_COUNT;
                        msg.obj=updateOnlineMsg.getOnline();
                        handler.sendMessage(msg);
                    }
                    return;
                case Constants.AV_IM_CMD_SYSTEM_COMMON_MSG://系统公告消息
                    SystemMsg systemMsg=gson.fromJson(msgModel.getActionParam(),SystemMsg.class);
                    msg.obj=systemMsg;
                    break;
                case Constants.AV_IM_CMD_NOTICE_GOOD:
                case Constants.AVIMCMD_Praise://点赞消息
                    GoodMsg goodMsg=gson.fromJson(msgModel.getActionParam(),GoodMsg.class);
                    goodMsg.setShowInList(false);
                    if(goodMsg.getFuser()!=null){
                        KKYUtil.log("第一次点赞消息");
                        hostGoodCount++;//累加点赞量
                        CurLiveInfo.setAdmires(hostGoodCount);
                        goodMsg.setShowInList(true);
                    }
                    msg.obj=goodMsg;
                    break;
                case Constants.AV_IM_CMD_NOTICE_GIFT://送礼消息
                    KKYUtil.log("收到礼物消息");
                    if(KKYApp.getInstance().GIFTS.size()>0) {
                        IMGiftMsg giftMsg=gson.fromJson(msgModel.getActionParam(),IMGiftMsg.class);
                        MsgSender giftMsgSender =giftMsg.getFuser();
                        if(giftMsgSender ==null|| giftMsgSender.getUid()==null||"".equals(giftMsgSender.getUid())|| giftMsgSender.getAvatar()==null){
                            KKYUtil.log("礼物发送者信息不全...,不显示");
                            return;
                        }
                        boolean isUpdateByLocal=false;//是否已匹配列表数据更新礼物信息
                        try {
                            for (Gift g : KKYApp.getInstance().GIFTS) {
                                if (giftMsg.getGiftid().equals(g.getId())) {
                                    giftMsg.setFlv(g.getFlv());
                                    giftMsg.setIcon(g.getIcon());
                                    giftMsg.setName(g.getName());
                                    giftMsg.setPrice(Integer.parseInt(g.getPrice()));
                                    isUpdateByLocal=true;
                                    liveIncoming=liveIncoming+giftMsg.getPrice();
                                    break;
                                }
                            }
                        }catch (NumberFormatException e){
                            return;
                        }
                        if(!isUpdateByLocal){
                            return;
                        }
                        String flv = giftMsg.getFlv();
                        msg.obj = giftMsg;
                        if ("0".equals(flv)) {
                            msg.what = INSERT_GIFT_ANIM;
                        } else if("1".equals(flv)) {
                            msg.what = INSERT_FRAME_GIFT_ANIM;//高级礼物
                        }else{
                           msg.obj=null;
                        }
                    }
                    break;
                case Constants.AV_IM_CMD_NOTICE_MUTE://禁言通知
                    ManageMsg muteMsg=gson.fromJson(msgModel.getActionParam(),ManageMsg.class);
                    muteMsg.setAction(msgModel.getUserAction());
                    checkMute(muteMsg.getTuser().getUid());//检测禁言
                    msg.obj=muteMsg;
                    break;
                case Constants.AV_IM_CMD_NOTICE_ADD_ADMIN://设置管理员通知
                    ManageMsg adminMsg=gson.fromJson(msgModel.getActionParam(),ManageMsg.class);
                    adminMsg.setAction(msgModel.getUserAction());
                    if(MySelfInfo.getInstance().getId().equals(adminMsg.getTuser().getUid())) {
                        if (isShowing()) {
                            mRoom.alert("您已被设为管理员！",null);
                        }
                    }
                    msg.obj=adminMsg;
                    break;
                case Constants.AV_IM_CMD_NOTICE_CANCEL_ADMIN://取消管理员通知
                case Constants.AV_IM_CMD_NOTICE_ATTENTION://关注主播通知
                    ManageMsg manageMsg=gson.fromJson(msgModel.getActionParam(),ManageMsg.class);
                    manageMsg.setAction(msgModel.getUserAction());
                    msg.obj=manageMsg;
                    break;
                default:
                    break;
            }
            if(msg.obj!=null){
                handler.sendMessage(msg);
            }
        }catch (NullPointerException e){
            e.printStackTrace();
            if(KKYUtil.DEBUG){
                mainView.showTopMsg(getContext().getString(R.string.room_show_msg_err)+e.getMessage());
            }
        }catch (IOException e){
            e.printStackTrace();
            if(KKYUtil.DEBUG){
                mainView.showTopMsg(getContext().getString(R.string.room_show_msg_err)+e.getMessage());
            }
        }catch (JsonParseException e){
            if(KKYUtil.DEBUG){
                mainView.showTopMsg(getContext().getString(R.string.room_show_msg_err)+e.getMessage());
            }
            e.printStackTrace();
        }
    }


    /**
     * 收到IM文本消息
     */
    public void onReceiveTxtMsg(TIMMessage currMsg,TIMTextElem elem){
        try {
            CommonMsg commonMsg = gson.fromJson(elem.getText(), CommonMsg.class);
            if("1".equals(commonMsg.getType())){//弹幕消息
                KKYUtil.log("收到IM弹幕消息:"+elem.getText());
                flyWordsView.waitFly(commonMsg);//插入弹幕
                //return;
            }
            KKYUtil.log("收到IM普通消息:"+elem.getText());
            Message msg=handler.obtainMessage();
            msg.what=SHOW_MSG;
            if(commonMsg!=null) {
                msg.obj = commonMsg;
            }
            handler.sendMessage(msg);
        }catch (JsonParseException e){
            if(KKYUtil.DEBUG){
                mainView.showTopMsg(getContext().getString(R.string.room_show_msg_err)+e.getMessage());
            }
        }catch (NullPointerException e){
            if(KKYUtil.DEBUG){
                mainView.showTopMsg(getContext().getString(R.string.room_show_msg_err)+e.getMessage());
            }
        }
    }

    public void handleMsg(Message msg) {
        int index=-1;
        switch (msg.what){
            case INSERT_FRAME_GIFT_ANIM:
                IMGiftMsg frameGiftMsg=(IMGiftMsg)msg.obj;
                frameAnimList.add(frameGiftMsg);
                //更新票数
                try {
                    long incoming = frameGiftMsg.getPrice();
                    currentGain=currentGain+incoming;
                    refreshTicketsCount();
                }catch (NumberFormatException e){
                    if(KKYUtil.DEBUG){
                        mainView.showTopMsg(getContext().getString(R.string.room_show_msg_err)+e.getMessage());
                    }
                }
                if(msgList.size()==100){//最多显示100条信息
                    msgList.remove(0);
                }
                msgList.add(msg.obj);
                try {
                    msgListAdapter.notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                }
                msgListView.smoothScrollToPosition(100);
                break;
            case INSERT_GIFT_ANIM:
                IMGiftMsg giftMsg=(IMGiftMsg)msg.obj;
                //更新票数
                try {
                    long incoming = giftMsg.getPrice();
                    currentGain=currentGain+incoming;
                    refreshTicketsCount();
                }catch (NumberFormatException e){
                    if(KKYUtil.DEBUG){
                        mainView.showTopMsg(getContext().getString(R.string.room_show_msg_err)+e.getMessage());
                    }
                }
                updateMsgList(giftMsg);
            case SHOW_MSG:
                if(msg.obj instanceof GoodMsg){
                    GoodMsg goodMsg=(GoodMsg)msg.obj;
                    boolean goodAnim=true;
                    if(goodMsg.getFuser()!=null){
                        if(MySelfInfo.getInstance().getId().equals(goodMsg.getFuser().getUid())){//自己的点的赞消息，不显示动画
                            goodAnim=false;
                        }
                    }
                    if(goodAnim){
                        try {
                            String praiseColorCode=goodMsg.getStar();
                            int num=Integer.parseInt(goodMsg.getNum());
                            KKYUtil.log("消息触发点赞消息..");
                            praiseAnimView.playAnim(praiseColorCode,num);//触发点赞动画
                        }catch (NumberFormatException e){

                        }
                    }
                    if(!goodMsg.isShowInList()){//不是第一次点赞消息，不显示在列表中
                        return;
                    }
                }
                if(msgList.size()==100){//最多显示100条信息
                    msgList.remove(0);
                }
                msgList.add(msg.obj);
                try {
                    msgListAdapter.notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                }
                msgListView.smoothScrollToPosition(100);
                break;
            case ANIM_READY:
            case CHECK_CONTINUE:
                index=(int)msg.obj;
                if(index==0){
                    if(animViewFirst.getAnimCount()<animViewFirst.getCount()){
                        handler.removeMessages(ANIM_FINISH_0);
                        animViewFirst.state=GiftAnimView.ANIM_COUNT;
                        animViewFirst.startCountAnim();
                    }else {
                        animViewFirst.state=GiftAnimView.WAIT_COUNT;
                        handler.sendEmptyMessageDelayed(ANIM_FINISH_0,3000);//预备结束
                    }
                }else if(index==1){
                    if(animViewSecond.getAnimCount()<animViewSecond.getCount()){
                        animViewSecond.state=GiftAnimView.ANIM_COUNT;
                        handler.removeMessages(ANIM_FINISH_1);
                        animViewSecond.startCountAnim();
                    }else {
                        animViewSecond.state=GiftAnimView.WAIT_COUNT;
                        handler.sendEmptyMessageDelayed(ANIM_FINISH_1,3000);//预备结束
                    }
                }
                break;
            case ANIM_FINISH_0:
                animViewFirst.state= GiftAnimView.COUNT_FINISH;
                animViewFirst.finish();
                break;
            case ANIM_FINISH_1:
                animViewSecond.state= GiftAnimView.COUNT_FINISH;
                animViewSecond.finish();
                break;
            case ANIM_HIDE:
                index=(int)msg.obj;
                if(index==0){
                    animViewFirst.state= GiftAnimView.HIDE;
                    animViewFirst.setVisibility(View.INVISIBLE);
                    animViewFirst.hide();
                }else if(index==1){
                    animViewSecond.state= GiftAnimView.HIDE;
                    animViewSecond.setVisibility(View.INVISIBLE);
                    animViewSecond.hide();
                }
                break;
            case READ_GIFT_ANIM:
                if(animViewFirst.state==GiftAnimView.HIDE){
                    readGiftAnim(0);
                }
                if(animViewSecond.state==GiftAnimView.HIDE){
                    readGiftAnim(1);
                }
                break;
            case HANDLE_SEND_LIKE:
                sendPraise(msg.obj.toString());
                break;
            case READ_FRAME_GIFT_ANIM:
                if(!isPlayFrameAnim) {
                    readFrameAnim();
                }
                break;
            case CLEAR_FRAME_GIFT_ANIM:
                if(framesAnimView!=null) {//退出时Surface会先调用销毁，并回调方法，异频调用冲突
                    framesAnimView.setVisibility(View.GONE);
                }
                isPlayFrameAnim=false;
                break;
            case HANDLE_HIDE_MULTI_VIDEO_BTN:

                break;
            case HANDLE_SHOW_MULTI_VIDEO_BTN:

                break;
            case HANDLE_REFRESH_ONLINE_BY_ENTER:
                if(msg.obj!=null){
                   refreshOnline(true,msg.obj);
                }
                break;
            case HANDLE_REFRESH_ONLINE_BY_EXIT:
                if(msg.obj!=null){
                    refreshOnline(false,msg.obj);
                }
                break;
            case HANDLE_HOST_BROADCAST_ONLINE:
                onHostSendUpdateOnlineMsg();
                break;
            case HANDLE_UPDATE_ONLINE_COUNT:
                if(msg.obj!=null&&TextUtils.isDigitsOnly(msg.obj.toString())){
                    mOnlineCount=Long.parseLong(msg.obj.toString());
                    topOnlineTv.setText(""+mOnlineCount);//更新在线人数数量
                }
                break;
            case HANDLE_SHOW_JOIN_MSG:
                showJoinMsg((EnterMsg)msg.obj);
                break;
            case HANDLE_HIDE_JOIN_MSG_VIEW:
                if(joinMsgView.getVisibility()==View.VISIBLE){
                    joinMsgView.setVisibility(View.INVISIBLE);
                }
                break;
            case HANDLE_UPDATE_MSG_COUNT:
                updateMsgCountView();
                break;
            default:
                break;
        }
    }

    /**
     * 显示某某进入房间的消息
     * @param msg
     */
    private void showJoinMsg(EnterMsg msg){
        try {
            handler.removeMessages(HANDLE_HIDE_JOIN_MSG_VIEW);
            if(joinMsgView.getVisibility()!=View.VISIBLE){
                joinMsgView.setVisibility(View.VISIBLE);
            }
            JOIN_MSG.clear();
            String name=msg.getFuser().getNickname();
            JOIN_MSG.append(CommonMsgListAdapter.tempIconStr).append(" ").append(name).append("  ").append(joinMsgSuffix);
            int lvl=msg.getFuser().getLvl();
            JOIN_MSG.setSpan(KKYApp.getLvSpan(lvl, mLvSpanWidth, mLvSpanHeight), 0, CommonMsgListAdapter.tempIconStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            JOIN_MSG.setSpan(CommonMsgViewHolder.nickSpan, CommonMsgListAdapter.tempIconStr.length()+1, CommonMsgListAdapter.tempIconStr.length() + name.length()+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            JOIN_MSG.setSpan(JOIN_COLOR_SPAN,CommonMsgListAdapter.tempIconStr.length() + name.length()+3, JOIN_MSG.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            joinMsgView.setText(JOIN_MSG);
        }catch (NullPointerException e){

        }
        handler.sendEmptyMessageDelayed(HANDLE_HIDE_JOIN_MSG_VIEW,3000);
    }

    /**
     * 刷新礼券数显示
     */
    private void refreshTicketsCount(){
        ticketsCountText.clear();
        ticketsCountText.append(gainLabel).append(" "+currentGain);
        ticketsCountText.setSpan(TICKETS_SPAN,gainLabel.length(),ticketsCountText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        gainValueTv.setText(ticketsCountText);
    }

    @Override
    public void onInterceptTouch(MotionEvent ev) {
        if(isShowKeyBoard&&mInputBar!=null&&mInputBar.getVisibility()==View.VISIBLE){
            mInputBar.getGlobalVisibleRect(inputBarRect);
            if(ev.getY()<inputBarRect.top){
                hideSoftInput(mInput);
            }
        }
    }

    /**
     * 礼物面板回调.
     *
     * 礼物选择面版关闭时回调
     */
    @Override
    public void onGiftPanelHide() {
        msgBox.setVisibility(View.VISIBLE);
        mBottomBarMenus.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSendGiftErrMsg(String msg) {
        if(mainView!=null){
            mainView.showTopMsg(msg);
        }
    }

    /**
     * 送礼发生升级
     * @param newLevel
     */
    @Override
    public void onLevelUp(int newLevel) {
        currentLvl=newLevel;
        if (MySelfInfo.getInstance().getIdStatus() != Constants.HOST) {
            //等级大于5级可连麦
            if (currentLvl >= Constants.INTERACT_MIN_LVL) {
                if (multiVideoBtn.getVisibility() != View.VISIBLE) {
                    multiVideoBtn.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_room_window:
                if(MySelfInfo.getInstance().getIdStatus()==Constants.MEMBER) {
                    checkSendPraise(false);
                    praiseAnimView.play(praiseColorCode);
                }
                break;
            case R.id.main_room_attention_opera_btn:
                handler.removeMessages(HANDLE_HIDE_ATTENTION);
                attentionUser();
                break;
            case R.id.main_room_window_user_info_head_view:
                onShowUserWindow(CurLiveInfo.getHostID());
                break;
            case R.id.gain_link:
                goRank();
                break;
            case R.id.main_room_window_open_input_btn:
                openInputBoard();
                break;
            case R.id.main_room_window_open_msg_board_btn:
                openMsgBoard();
                break;
            case R.id.main_room_window_host_open_share_menus_btn:
            case R.id.main_room_window_open_share_menus_btn:
                openShareMenus();
                break;
            case R.id.main_room_window_open_gift_box_btn:
                openGiftBox();
                break;
            case R.id.main_room_window_camera_menus_btn:
                roomPresenter.switchCamera();
                break;
            case R.id.main_room_window_flashlight_menus_btn:
                switchFlashlight();
                break;
            case R.id.main_room_window_bottom_bar_send_btn:
                onSendCommonMsg(mInput.getText().toString());
                break;
            case R.id.main_room_window_exit_btn:
            case R.id.main_room_window_host_exit_btn:
                onExitLive();
                break;
            case R.id.multi_video_opera_btn:
                if(mRoom!=null){
                    mRoom.onClick(v);
                }
                break;
            case R.id.main_room_window_open_game_menus_icon://打开游戏界面
            case R.id.main_room_window_open_game_menus_icon_://打开游戏界面
                //Intent game=new Intent(getContext(), RoomWebGame.class);
                //getContext().startActivity(game);
                break;
            default:
                break;
        }
    }

    /**
     * 关注主播
     */
    protected void attentionUser(){

    }

    /**
     * 用户加入房间
     */
    public void onMemberJoin(EnterMsg enterMsg){
        try {
            KKYUtil.log(enterMsg.getFuser().getNickname()+"我进入了房间...."+enterMsg.getFuser().getUid());
            Message msg=handler.obtainMessage();
            msg.what=HANDLE_SHOW_JOIN_MSG;
            msg.obj=enterMsg;
            handler.sendMessage(msg);
            String id=enterMsg.getFuser().getUid();
            if(!onlineIds.containsKey(id)){
                onlineIds.put(id,id);
                //增加一个在线人数
                msg=handler.obtainMessage();
                msg.what=HANDLE_REFRESH_ONLINE_BY_ENTER;
                MemberInfo m=new MemberInfo();
                m.setUid(id);
                m.setNickname(enterMsg.getFuser().getNickname());
                m.setAvatar(enterMsg.getFuser().getAvatar());
                msg.obj=m;
                handler.sendMessage(msg);
            }
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }

    /**
     * 用户离开房间
     */
    public void onMemberExit(String id){
        KKYUtil.log("我离开了房间...."+id);
        if(onlineIds.containsKey(id)){
            //移除一个在线人数
            onlineIds.remove(id);
            Message message=handler.obtainMessage();
            message.what=HANDLE_REFRESH_ONLINE_BY_EXIT;
            message.obj=id;
            handler.sendMessage(message);
        }
    }

    /***
     * 在线观从列表
     */
    public void onHostSendUpdateOnlineMsg() {
        if(isBroadcastOnline){
            isBroadcastOnline=false;
            if(MySelfInfo.getInstance().getIdStatus()!=Constants.HOST){//非主播
                mOnlineCount=members.size();
                topOnlineTv.setText(""+mOnlineCount);//更新在线人数数量
                return;
            }
            int realCount=(int)mRealOnlineCount;
            if(updateOnlineMsg==null){
                updateOnlineMsg=new MsgModel();
            }
            if(updateOnline==null){
                updateOnline=new UpdateOnlineMsg(mOnlineCount+"");
            }
            int tempCount=0;
            if(!CurLiveInfo.isPrivate) {//公开直播才会有机器人数据随机
                if(realCount==0){
                    realCount=1;
                }
                for (int i = 0; i < realCount; i++) {
                    int count = countRandom.nextInt(MAX_RANDOM_COUNT);
                    tempCount += count > MIN_RANDOM_COUNT ? count : MIN_RANDOM_COUNT;
                }
                mOnlineCount=tempCount+mRobotCount;
            }else{
                mOnlineCount=mRealOnlineCount;
            }
            KKYUtil.log("广播在线人数："+mOnlineCount);
            updateOnline.setOnline(mOnlineCount+"");
            if(mOnlineCount>0){
                mRoom.onHostInitOnlineCount(mOnlineCount);//初始化心跳上报的人数并立即上报
            }
            topOnlineTv.setText(""+mOnlineCount);//更新在线人数数量
            mRoom.syncWatchCount(mOnlineCount);
            updateOnlineMsg.setUserAction(Constants.AV_IM_CMD_MEMBER_UPDATE_ONLINE);
            updateOnlineMsg.setActionParam(gson.toJson(updateOnline));
            roomPresenter.sendGroupNoticeMessage(gson.toJson(updateOnlineMsg),new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {

                }

                @Override
                public void onSuccess(TIMMessage message) {

                }
            });//高级别消息
        }
        handler.sendEmptyMessageDelayed(HANDLE_HOST_BROADCAST_ONLINE,10*1000);//10秒后再发
    }




    /**
     * 加载房间在线列表1.1
     */
    private void loadOnline(long page){
        TIMGroupManager.getInstance().getGroupMembersV2(CurLiveInfo.getChatRoomId(), 0, null, page, new TIMValueCallBack<TIMGroupMemberSuccV2>() {
            @Override
            public void onError(int i, String s) {

            }
            /**
             * 取到一页数据，只能获取到ids
             * @param timGroupMemberSuccV2
             */
            @Override
            public void onSuccess(TIMGroupMemberSuccV2 timGroupMemberSuccV2) {
                List<TIMGroupMemberInfo> timGroupMemberInfo = timGroupMemberSuccV2.getMemberInfoList();
                KKYUtil.log("本次拉到成员数："+timGroupMemberInfo.size());
                List<String>users=new ArrayList<String>();
                for (TIMGroupMemberInfo info : timGroupMemberInfo) {
                    users.add(info.getUser());
                }
                mNextSeq=timGroupMemberSuccV2.getNextSeq();
                loadOnline(users);
            }
        });
    }

    /**
     * 加载房间在线列表1.2
     */
    private void loadOnline(List<String>ids){
        for (String id:ids){
            KKYUtil.log("拉取ID列表："+id);
        }
        //获取用户资料
        TIMFriendshipManager.getInstance().getUsersProfile(ids, new TIMValueCallBack<List<TIMUserProfile>>(){
            @Override
            public void onError(int code, String desc){

            }

            @Override
            public void onSuccess(List<TIMUserProfile> result){
                if(result.size()>0){
                    List<MemberInfo>members=new ArrayList<MemberInfo>();
                    Message message=handler.obtainMessage();
                    message.what=HANDLE_REFRESH_ONLINE_BY_ENTER;
                    for (TIMUserProfile res : result) {
                        if(CurLiveInfo.hostID.equals(res.getIdentifier())){//不添加主播到列表
                            continue;
                        }
                        if(MySelfInfo.getInstance().getId().equals(res.getIdentifier())){//不添加自己到列表
                            //continue;
                        }
                        if(!onlineIds.contains(res.getIdentifier())){//未添加到在线列表，则添加
                            onlineIds.put(res.getIdentifier(),res.getIdentifier());
                            KKYUtil.log("在线观众头像：" + res.getFaceUrl());
                            MemberInfo memberInfo = new MemberInfo();
                            memberInfo.setUid(res.getIdentifier());
                            memberInfo.setNickname(res.getNickName());
                            memberInfo.setAvatar(res.getFaceUrl());
                            members.add(memberInfo);
                        }
                    }
                    if(members.size()>0){
                        message.obj=members;
                        handler.sendMessage(message);
                    }
                }
                //如果在线观众列表小于25个
                if(onlineIds.size()<25){
                    if(mNextSeq!=0){//有下一页
                       loadOnline(mNextSeq);
                    }else{
                       //没有加载过机器人，用机器人补充
                       if(!isLoadedRobotList){
                           loadRobots();
                       }
                    }
                }
            }
        });
    }

    /**
     * 加载机器人冒充人类1.3
     */
    private void loadRobots(){
        if(CurLiveInfo.isPrivate){//私密直播不加载机器人
            isLoadedRobotList=true;
            return;
        }
        KKYUtil.log("请求加载机器人数据");
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("rid", CurLiveInfo.getHostID());
        OKHttp.post(HttpConfig.API_GET_ROBOT_LIST, param.jsonParam(), "loadRobot", new OKHttpUIHandler(RobotModel.class) {
            @Override
            public void onSuccess(Object model) {
                RobotModel m = (RobotModel) model;
                KKYUtil.log("加载机器人数据：" + m.getResponseStr());
                try {
                    List<String> list=m.getData().getList();
                    mRobotCount=list.size();
                    loadOnline(list);
                    isLoadedRobotList=true;
                }catch (Exception e){

                }
            }

            @Override
            public void onErr(String errMsg) {

            }
        });
    }


    /**
     * 刷新观众列表1.4
     * @param isEnter 加入观众到列表
     * @param obj
     */
    public void refreshOnline(boolean isEnter,Object obj){
        try {
            if(isEnter){
                if(onlineIds.size()<1000){//最多显示1000个
                    if(obj instanceof List){
                        List list_=(List)obj;
                        if(list_.size()>0&&list_.get(0) instanceof MemberInfo){
                            members.addAll(list_);
                        }
                    }else if(obj instanceof MemberInfo){
                        mRealOnlineCount++;
                        mOnlineCount++;
                        members.add(0,(MemberInfo)obj);
                        isBroadcastOnline=true;
                    }
                }
            }else{
                if(mRealOnlineCount>0){
                    mRealOnlineCount--;
                }
                if(mOnlineCount>0){
                    mOnlineCount--;
                }
                String id=obj.toString();
                for (int i=0;i<members.size();i++){
                    if(id.equals(members.get(i).getUid())){
                        isBroadcastOnline=true;
                        members.remove(i);
                        break;
                    }
                }
            }
            topOnlineTv.setText(""+mOnlineCount);//更新在线人数数量
            mOnlineAdapter.notifyDataSetChanged();
        }catch (Exception e){
            Toast.makeText(getContext(),"观众列表异常",Toast.LENGTH_LONG).show();
            CrashReport.postCatchedException(e);
        }
    }


    /**
     * 弹出用户卡信息
     * @param uid
     */
    @Override
    public void onShowUserWindow(String uid) {

    }

    /**
     * 跳转到系统消息连接的WebView
     */
    public void goSystemWeb(String title,String url){
        KKYUtil.log("跳转到系统消息连接@"+url);
    }

    /**
     * 查看票数贡献排行
     */
    protected void goRank(){
        KKYUtil.log("查看票数贡献排行");
    }

    /**
     * 打开输入面板
     */
    protected void openInputBoard(){
        topBox.clearAnimation();
        topBox.startAnimation(topBoxOutAni);
        currentGainLink.getGlobalVisibleRect(currentGainLinkRect);
        userGainBtnOutX.setFloatValues(0,-currentGainLinkRect.width());
        userGainBtnOutAnim.start();
        mBottomBarMenus.setVisibility(View.INVISIBLE);
        mInputBar.setVisibility(View.VISIBLE);
        showSoftInput(mInput);
    }

    /**
     * 打开私信面板
     */
    protected void openMsgBoard(){
        KKYUtil.log("打开私信面板...");
    }

    /**
     * 打开分享选择菜单
     */
    protected void openShareMenus(){
        KKYUtil.log("打开分享菜单...");
    }

    /**
     * 弹出礼物盒子
     */
    protected void openGiftBox(){
        if(KKYApp.getInstance().GIFTS.size()==0|| KKYApp.getInstance().GIFTS_PAGES.size()==0){
            mainView.showTopMsg(getContext().getString(R.string.room_gift_board_err));
            return;
        }
        msgBox.setVisibility(View.INVISIBLE);
        mBottomBarMenus.clearAnimation();
        mBottomBarMenus.startAnimation(bottomBarOutAnim);
        if(giftPanel!=null){
            giftPanel.show(this,roomInfo,mMsgSender,currentLvl,roomPresenter);
        }
    }


    /**
     * 切换闪光灯
     */
    public void switchFlashlight(){
        if(isCanSwitchLight){
            if(roomPresenter !=null){
                roomPresenter.toggleFlashLight();
            }
            flashlightOff=!flashlightOff;
            //如果是打开状态,指示关闭
            if(!flashlightOff){
                flashlightSwitch.setImageResource(R.mipmap.flashlight_option_off_icon);
            }else{
                flashlightSwitch.setImageResource(R.mipmap.flashlight_option_on_icon);
            }
        }
    }

    /**
     * 退出直播
     */
    protected void onExitLive(){
        onKeyDown(KeyEvent.KEYCODE_BACK, null);
    }

    /**
     * 发送聊天消息
     */
    protected void onSendCommonMsg(String msg){

    }


    /**
     * 处理禁言通知
     */
    protected void checkMute(String uid){
        if(MySelfInfo.getInstance().getId().equals(uid)){
            sp=getContext().getSharedPreferences(MUTE_STATE,Context.MODE_PRIVATE);
            sp.edit().putLong(MUTE_EXPIRE_AT+CurLiveInfo.getHostID(),System.currentTimeMillis()+MAX_MUTE_TIME).commit();
        }
    }

    /**
     * 开始检查礼物动画列表
     */
    private void startCheckAnimList(){
        try {
            if(checkGiftAnimListTimer==null){
                checkGiftAnimListTimer=new Timer(true);
            }
            if(checkGiftAnimListTask==null){
                checkGiftAnimListTask=new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(READ_GIFT_ANIM);
                    }
                };
            }
            checkGiftAnimListTimer.schedule(checkGiftAnimListTask,0,500);
            if(readFrameAnimTask==null){
                readFrameAnimTask=new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(READ_FRAME_GIFT_ANIM);
                    }
                };
            }
            readFrameAnimTimer.schedule(readFrameAnimTask, 0, 1000);
        }catch (IllegalStateException e){
            mainView.showTopMsg(getContext().getString(R.string.room_play_anim_err));
            if(getOwnerActivity()!=null){
                dismiss();
                getOwnerActivity().onBackPressed();
            }
            CrashReport.postCatchedException(e);
        }
    }

    /**
     * 读取礼物动画
     */
    private void readGiftAnim(int index){
        if(giftAnimList.size()>0){
            GiftAnim anim = giftAnimList.get(0);
            String nick=anim.getMsgList().get(0).getFuser().getNickname();
            String avatar=anim.getMsgList().get(0).getFuser().getAvatar();
            String msg=anim.getMsgList().get(0).getName();
            String icon=anim.getMsgList().get(0).getIcon();
            if(index==0){
                animViewFirst.state=GiftAnimView.STARTED;
                animViewFirst.setKey(anim.getKey());
                animViewFirst.setGiftAnim(anim);
                animViewFirst.updateInfo(avatar,nick,msg,icon);
                animViewFirst.setVisibility(View.VISIBLE);
                animViewFirst.enter();
            }else{
                animViewSecond.state=GiftAnimView.STARTED;
                animViewSecond.setKey(anim.getKey());
                animViewSecond.setGiftAnim(anim);
                animViewSecond.updateInfo(avatar,nick,msg,icon);
                animViewSecond.setVisibility(View.VISIBLE);
                animViewSecond.enter();
            }
            giftAnimList.remove(0);
        }
    }

    /**
     * 刷新礼物动画队列
     *
     */
    private void updateMsgList(IMGiftMsg msg){
        String msgKey=msg.getFuser().getUid()+msg.getGiftid();//用户id和礼物id组成key
        long timestamp=msg.getTime();//时间戳
        KKYUtil.log("收到礼物消息时间戳："+timestamp);
        if(msgKey.equals(animViewFirst.getKey())){
            GiftAnim anim=animViewFirst.getGiftAnim();
            List<IMGiftMsg>list=anim.getMsgList();
            int size=list.size();
            if(size!=0) {
                IMGiftMsg lastMsg = list.get(size-1);//最近一条信息
                long diffTime = timestamp - lastMsg.getTime();
                KKYUtil.log("最近上一条礼物消息时间戳："+lastMsg.getTime());
                KKYUtil.log("时间差："+diffTime);
                if (diffTime < 4) {//时间差小于3秒则连动画
                    list.add(msg);//添加一跳，判断是否动画跳
                    animViewFirst.setCount();//累加总计数
                    if(animViewFirst.state==GiftAnimView.WAIT_COUNT) {
                        animViewFirst.state = GiftAnimView.ANIM_COUNT;
                        handler.removeMessages(ANIM_FINISH_0);
                        animViewFirst.startCountAnim();
                    }
                    return;
                }else{
                    list.clear();
                }
            }
        }

        if(msgKey.equals(animViewSecond.getKey())){
            GiftAnim anim=animViewSecond.getGiftAnim();
            List<IMGiftMsg>list=anim.getMsgList();
            int size=list.size();
            if(size!=0) {
                IMGiftMsg lastMsg = list.get(size-1);//最后一条信息
                long diffTime = timestamp - lastMsg.getTime();
                if (diffTime < 3) {//时间差小于3秒则连动画
                    list.add(msg);//添加一跳，判断是否动画跳
                    animViewSecond.setCount();//累加总计数
                    if(animViewSecond.state==GiftAnimView.WAIT_COUNT) {
                        animViewSecond.state = GiftAnimView.ANIM_COUNT;
                        handler.removeMessages(ANIM_FINISH_1);
                        animViewSecond.startCountAnim();
                    }
                    return;
                }
            }
        }

        boolean isNewAnim=true;
        for (int i=0;i<giftAnimList.size();i++){
            GiftAnim anim=giftAnimList.get(i);
            if(msgKey.equals(anim.getKey())) {
                List<IMGiftMsg> list = anim.getMsgList();
                int size = list.size();
                if (size != 0) {
                    IMGiftMsg lastMsg = list.get(size - 1);//最后一条信息
                    long diffTime = timestamp - lastMsg.getTime();
                    if (diffTime < 3) {//时间差小于3秒则连动画
                        list.add(msg);//添加一跳，判断是否动画跳
                        isNewAnim=false;
                        break;
                    }
                }
            }
        }
        if(isNewAnim) {
            GiftAnim g = new GiftAnim();
            g.setKey(msgKey);
            g.getMsgList().add(msg);
            giftAnimList.add(g);
        }
    }

    /**
     * 读取帧动画
     */
    private void readFrameAnim(){
        if(frameAnimList.size()>0){
            IMGiftMsg msg=frameAnimList.get(0);
            String path = "giftFrames/frame_" + msg.getGiftid();
            //path = "giftFrames/frame_10008";
            playFrameAnim(path);
            frameAnimList.remove(0);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 播放高级帧动画
     */
    public void playFrameAnim(String key){
        KKYUtil.log("播放帧动画"+key);
        isPlayFrameAnim=true;
        if(framesAnimView.getVisibility()==View.GONE){
            framesAnimView.setVisibility(View.VISIBLE);
        }
        framesAnimView.play(key);
    }

    /**
     * 连麦按钮是否可用
     * @param enable true可用
     */
    public void interactiveVideoEnable(boolean enable){
        multiVideoBtn.setEnabled(enable);
        /**
        if(enable){
            if(multiVideoBtn!=null&&multiVideoBtn.getVisibility()!=View.VISIBLE){
                //multiVideoBtn.setVisibility(View.VISIBLE);
            }
        }else{
            if(multiVideoBtn!=null&&multiVideoBtn.getVisibility()==View.VISIBLE){
                //multiVideoBtn.setVisibility(View.GONE);
            }
        }
         */
    }



    @Override
    public void show() {
        super.show();
        if(mMsgSender ==null){
            mMsgSender =new MsgSender();
            MySelfInfo.getInstance().getCache(getContext());
            mMsgSender.setUid(MySelfInfo.getInstance().getId());
            mMsgSender.setNickname(MySelfInfo.getInstance().getNickName());
            mMsgSender.setAvatar(MySelfInfo.getInstance().getAvatar());
            mMsgSender.setLvl(MySelfInfo.getInstance().getLvl());
        }
        hostGoodCount=0;
        roomPresenter =mRoom.mRoomPresenter;
        //连接聊天室
        startCheckAnimList();//开始检测动画列表
        loadOnline(0);//加载观从列表
        if(MySelfInfo.getInstance().getIdStatus()==Constants.HOST){//主播
            onHostSendUpdateOnlineMsg();//广播在线人数
        }
    }

    @Override
    public void dismiss() {
        if(checkGiftAnimListTimer!=null){
            checkGiftAnimListTimer.cancel();
            checkGiftAnimListTimer=null;
        }
        if(checkGiftAnimListTask!=null){
            checkGiftAnimListTask.cancel();
            checkGiftAnimListTask=null;
        }
        if(checkPraiseCountTimer!=null){
            checkPraiseCountTimer.cancel();
            checkPraiseCountTimer=null;
        }
        if(checkPraiseCountTask!=null){
            checkPraiseCountTask.cancel();
            checkPraiseCountTask=null;
        }
        if(readFrameAnimTimer!=null){
            readFrameAnimTimer.cancel();
            readFrameAnimTimer=null;
        }
        if(readFrameAnimTask!=null){
            readFrameAnimTask.cancel();
            readFrameAnimTask=null;
        }
        if(msgListAdapter!=null){
            msgListAdapter.setWin(null);
        }
        if(praiseAnimView!=null){
            praiseAnimView.destroy();
        }
        handler.removeCallbacksAndMessages(null);
        MsgCountManager.getInstance().deleteObserver(this);
        msgList.clear();
        giftAnimList.clear();
        roomPresenter =null;
        if(giftPanel!=null){
            giftPanel.destroy();
        }
        super.dismiss();
    }

    /**
     * 键盘隐藏
     */
    private void onBoardHide(){
        if(mInputBar!=null&&mInputBar.getVisibility()==View.VISIBLE){
            mInputBar.setVisibility(View.INVISIBLE);
        }
        if(mBottomBarMenus!=null&&mBottomBarMenus.getVisibility()!=View.VISIBLE){
            mBottomBarMenus.setVisibility(View.VISIBLE);
        }
        if(topBox!=null&&topBox.getVisibility()!=View.VISIBLE){
            topBox.setVisibility(View.VISIBLE);
            topBox.clearAnimation();
            topBox.startAnimation(topBoxEnterAni);
        }
        if(currentGainLink!=null&&currentGainLink.getVisibility()!=View.VISIBLE){
            currentGainLink.setVisibility(View.VISIBLE);
            userGainBtnEnterX.setFloatValues(-currentGainLinkRect.width(),0);
            userGainBtnEnterAnim.start();
        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //返回键盘事件
        if(keyCode==KeyEvent.KEYCODE_BACK){
             if(getOwnerActivity()!=null&&getOwnerActivity() instanceof RoomVideoRoom){
                ((RoomVideoRoom)getOwnerActivity()).onBackPressed();
             }
            return false;
            //return super.onKeyDown(keyCode,event);
        }else{
            return super.onKeyDown(keyCode,event);
        }
    }


    /**
     * 是否显示键盘
     */
    protected boolean isKeyboardVisible(View view){
        return (getDistanceFromInputToBottom(view) > DISTANCE_SLOP)
                || (getDistanceFromInputToBottom(view) >DISTANCE_SLOP);
    }

    /**
     * 输入框的下边距离屏幕的距离
     */
    private int getDistanceFromInputToBottom(View view) {
        return mScreenHeight - getInputBottom(view);
    }

    /**
     * 输入框下边的位置
     */
    private int getInputBottom(View view) {
        view.getGlobalVisibleRect(mMsgBoxRect);
        return mMsgBoxRect.bottom;
    }

    /**
     * 关闭键盘
     */
    protected void hideSoftInput(View input) {
        if(input == null) return;
        InputMethodManager imm = (InputMethodManager)getContext()
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 弹出键盘
     */
    protected void showSoftInput(View input) {
        if(input == null) return;
        input.requestFocus();
        ((InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE))
                .showSoftInput(input, 0);
    }

    static class IHandler extends Handler {
        private WeakReference<LiveRoomAnimWin> win;

        IHandler(LiveRoomAnimWin win) {
            this.win = new WeakReference<LiveRoomAnimWin>(win);
        }
        @Override
        public void handleMessage(Message msg) {
            win.get().handleMsg(msg);
        }
    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(mRoom!=null){
            mRoom.dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }
}
